#include "DX11TextureManager.h"
#include "MapFunctions.h"
#include "ScreenManager.h"
#include "DX11ErrorReport.h"

DX11TextureManager::DX11TextureManager()
{

}

void DX11TextureManager::Initialise()
{	
	D3D11_SAMPLER_DESC sampDesc;
	ZeroMemory( &sampDesc, sizeof(sampDesc) );
	sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
	sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
    sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sampDesc.MinLOD = 0;
    sampDesc.MaxLOD = D3D11_FLOAT32_MAX;

	TheScreenManager::Instance()->GetDevice()->CreateSamplerState(&sampDesc, &m_pDefaultSamplerState);
}

ID3D11SamplerState* DX11TextureManager::UseDefaultSamplerState() const
{
	return m_pDefaultSamplerState;
}

bool DX11TextureManager::LoadTexture(const std::wstring& filePath)
{
	TextureMap::iterator it = m_textures.find(filePath);
	if (it == m_textures.end())
	{
		m_textures[filePath] = NULL;
		HRESULT hr = S_OK;
		hr = D3DX11CreateShaderResourceViewFromFile(TheScreenManager::Instance()->GetDevice(), filePath.c_str(),
												NULL, NULL, &m_textures[filePath], NULL);
		if (FAILED(hr))
		{
			std::wstring errorMsg = L"Failed to load texture " + filePath;
			DX11ErrorMsg(errorMsg.c_str(), L"Texture Manager", MB_OK);
			return false;
		}
	}
	return true;
}

ID3D11ShaderResourceView*& DX11TextureManager::UseTexture(const std::wstring& texTag)
{
	CheckMapElement(m_textures, texTag);
	return m_textures[texTag];
}